package com.ray.system.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ray.common.SysMsgCodeConstant;
import com.ray.common.check.AbstractCheck;
import com.ray.system.builder.*;
import com.ray.system.check.PositionCheck;
import com.ray.system.check.RoleCheck;
import com.ray.system.check.UserCheck;
import com.ray.system.service.*;
import com.ray.system.service.compose.UserService;
import com.ray.system.table.dto.CompanyInfoDTO;
import com.ray.system.table.dto.UserInfoDTO;
import com.ray.system.table.dto.UserQueryDTO;
import com.ray.system.table.entity.*;
import com.ray.system.table.params.user.*;
import com.ray.system.table.vo.user.UserVO;
import com.ray.template.TemplateFactory;
import com.ray.template.TemplateRecord;
import com.ray.validate.support.utils.ValidateUtil;
import com.ray.woodencreate.beans.LoginUser;
import com.ray.woodencreate.enums.YesOrNoEnum;
import com.ray.woodencreate.exception.BusinessExceptionFactory;
import com.ray.woodencreate.page.CommonPage;
import com.ray.woodencreate.result.MsgCodeConstant;
import com.ray.woodencreate.result.Result;
import com.ray.woodencreate.result.ResultFactory;
import com.ray.woodencreate.util.Assert;
import com.ray.woodencreate.util.LogInUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author bo shen
 * @Description: 用户相关接口
 * @Class: UserApi
 * @Package com.ray.system.api
 * @date 2020/5/27 8:28
 * @User <p>杭州传化陆鲸科技有限用户</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
@Slf4j
@Service
public class UserApi {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserInfoService sysUserInfoService;
    @Autowired
    private SysUserCompanyService sysUserCompanyService;
    @Autowired
    private SysLoginService sysLoginService;
    @Autowired
    private SysUserPositionService sysUserPositionService;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysPositionService sysPositionService;
    @Autowired
    private SysOrganizationService sysOrganizationService;
    @Autowired
    private UserService userService;

    /**************运营相关***********************/

    /**
     * 开启用户--运营
     *
     * @param userCode 用户编码
     * @return Result
     */
    @Transactional
    public Result<String> openUserForManageer(String userCode) {
        ValidateUtil.hasLength(userCode, "参数[userCode]不能为空");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //获取权限信息
        SysUser sysUser = sysUserService.queryUserByUserCode(userCode, loginUser);
        new UserCheck(sysUser).checkNull(SysMsgCodeConstant.Error.ERR10000002);
        UserBuilder UserBuilder = new UserBuilder();
        UserBuilder.appendCode(userCode).appendEdit(loginUser).open();
        //开启用户信息
        if (!sysUserService.edit(UserBuilder.bulid(), loginUser)) {
            log.info("开启用户接口异常,参数:{}", JSON.toJSONString(UserBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, UserBuilder.getCode());
    }

    /**
     * 开启用户--运营
     *
     * @param userCode 用户编码
     * @return Result
     */
    @Transactional
    public Result<String> closeUserForManageer(String userCode) {
        ValidateUtil.hasLength(userCode, "参数[userCode]不能为空");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //获取权限信息
        SysUser sysUser = sysUserService.queryUserByUserCode(userCode, loginUser);
        new UserCheck(sysUser).checkNull(SysMsgCodeConstant.Error.ERR10000002);
        UserBuilder UserBuilder = new UserBuilder();
        UserBuilder.appendCode(userCode).appendEdit(loginUser).close();
        //关闭用户信息
        if (!sysUserService.edit(UserBuilder.bulid(), loginUser)) {
            log.info("关闭用户接口异常,参数:{}", JSON.toJSONString(UserBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, UserBuilder.getCode());
    }


    /**
     * 管理员获取用户列表
     * @param queryParams
     * @return
     */
    public Result<IPage<UserVO>> pageUsersForManager(CommonPage<UserManagerQueryParams, Page<UserVO>> queryParams) {
        Assert.notNull(queryParams, SysMsgCodeConstant.Error.ERR10000001);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        CommonPageBuilder<UserQueryDTO, SysUser> commonPageBuilder = new CommonPageBuilder<>(UserQueryDTO.class);
        commonPageBuilder.appendEntity(queryParams.getEntity()).appendQuery(queryParams.getQuery()).appendPage(queryParams.getPage());
        //获取当前用户对应公司的用户
        String companyCode = null;
        UserManagerQueryParams userQueryParams = queryParams.getEntity();
        if (ObjectUtil.isNotNull(userQueryParams)) {
            companyCode = userQueryParams.getCompanyCode();
        }
        if (StrUtil.isBlank(companyCode)) {
            companyCode = loginUser.getCompanyCode();
        }
        //循环使用
        final  String queryCompanyCode = companyCode;
        List<String> userCodes = sysUserCompanyService.queryUserByCompanyCode(companyCode, null)
                .stream().map(SysUserCompany::getUserCode).collect(Collectors.toList());
        //结果对象
        IPage<UserVO> pageList = new Page<>();
        if (ObjectUtil.isEmpty(userCodes)) {
            //无结果数据设置
            pageList.setTotal(0);
            pageList.setCurrent(queryParams.getPage().getCurrent());
            pageList.setSize(queryParams.getPage().getSize());
            pageList.setRecords(new ArrayList<>());
            //返回空列表
            return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, pageList);
        }
        IPage<SysUser> page = sysUserService.page(commonPageBuilder.bulid(), userCodes);
        List<SysUser> Users = page.getRecords();
        pageList.setTotal(page.getTotal());
        pageList.setCurrent(page.getCurrent());
        pageList.setSize(page.getSize());
        Map<String,SysPosition> positionMap = new HashMap<>();
        //查询到结果 数据转换
        if (ObjectUtil.isNotNull(Users)) {
            pageList.setRecords(Users.stream().map(sysUser -> {
                UserVO userVO = new UserVO();
                BeanUtil.copyProperties(sysUser, userVO);
                //获取职位信息
                SysPosition userPosition = positionMap.get(sysUser.getUserCode());
                if(ObjectUtil.isNull(userPosition)){
                    userPosition = userService.queryPositionByLogin(sysUser.getUserCode(),queryCompanyCode);
                    positionMap.put(sysUser.getUserCode(),userPosition);
                }
                if(ObjectUtil.isNotNull(userPosition)){
                    userVO.setPositionCode(userPosition.getPositionCode());
                    userVO.setPositionName(userPosition.getPositionName());
                }
                return userVO;
            }).collect(Collectors.toList()));
        } else {
            pageList.setRecords(new ArrayList<>());
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, pageList);
    }


    /************功能相关**********************/
    /**
     * 查询用户列表信息 分页  非删除的
     *
     * @param queryParams
     * @return
     */
    public Result<IPage<UserVO>> pageUsers(CommonPage<UserQueryParams, Page<UserVO>> queryParams) {
        Assert.notNull(queryParams, SysMsgCodeConstant.Error.ERR10000001);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        CommonPageBuilder<UserQueryDTO, SysUser> commonPageBuilder = new CommonPageBuilder<>(UserQueryDTO.class);
        commonPageBuilder.appendEntity(queryParams.getEntity()).appendQuery(queryParams.getQuery()).appendPage(queryParams.getPage());
        //获取当前用户对应公司的用户
        String deptCode = null;
        UserQueryParams userQueryParams = queryParams.getEntity();
        if (ObjectUtil.isNotNull(userQueryParams)) {
            deptCode = userQueryParams.getDeptCode();
        }
        Map<String, SysUserCompany> userMap = new HashMap<>();
        sysUserCompanyService.queryUserByCompanyCode(loginUser.getCompanyCode(), deptCode).forEach(sysUserCompany -> {
            userMap.put(sysUserCompany.getUserCode(), sysUserCompany);
        });

        //结果对象
        IPage<UserVO> pageList = new Page<>();
        if (ObjectUtil.isEmpty(userMap.keySet())) {
            pageList.setTotal(0);
            pageList.setCurrent(queryParams.getPage().getCurrent());
            pageList.setSize(queryParams.getPage().getSize());
            pageList.setRecords(new ArrayList<>());
            return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, pageList);
        }
        IPage<SysUser> page = sysUserService.page(commonPageBuilder.bulid(), userMap.keySet());
        List<SysUser> Users = page.getRecords();

        pageList.setTotal(page.getTotal());
        pageList.setCurrent(page.getCurrent());
        pageList.setSize(page.getSize());
        //查询到结果 数据转换
        if (ObjectUtil.isNotNull(Users)) {
            Map<String,SysPosition> positionMap = new HashMap<>();
            pageList.setRecords(Users.stream().map(sysUser -> {
                UserVO userVO = new UserVO();
                BeanUtil.copyProperties(sysUser, userVO);
                SysUserCompany sysUserCompany = userMap.get(sysUser.getUserCode());
                if (ObjectUtil.isNotNull(sysUserCompany)) {
                    userVO.setStatus(sysUserCompany.getStatus());
                    SysOrganization sysOrganization = sysOrganizationService.queryOrganizationByOrganizationCode(sysUserCompany.getDeptCode(), loginUser);
                    if (ObjectUtil.isNotNull(sysOrganization)) {
                        userVO.setDeptCode(sysOrganization.getDeptCode());
                        userVO.setDeptName(sysOrganization.getDeptName());
                    } else {
                        userVO.setDeptCode(loginUser.getCompanyCode());
                        userVO.setDeptName(loginUser.getCompanyName());
                    }
                    //获取职位信息
                    SysPosition userPosition = positionMap.get(sysUser.getUserCode());
                    if(ObjectUtil.isNull(userPosition)){
                        userPosition = userService.queryPositionByLogin(sysUser.getUserCode(),loginUser.getCompanyCode());
                        positionMap.put(sysUser.getUserCode(),userPosition);
                    }
                    if(ObjectUtil.isNotNull(userPosition)){
                        userVO.setPositionCode(userPosition.getPositionCode());
                        userVO.setPositionName(userPosition.getPositionName());
                    }
                }
                return userVO;
            }).collect(Collectors.toList()));
        } else {
            pageList.setRecords(new ArrayList<>());
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, pageList);
    }

    /**
     * 查询用户列表信息 分页  非删除的
     *
     * @param queryParams
     * @return
     */
    public Result<IPage<UserVO>> pageAll(CommonPage<UserQueryParams, Page<UserVO>> queryParams) {
        Assert.notNull(queryParams, SysMsgCodeConstant.Error.ERR10000001);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        CommonPageBuilder<UserQueryDTO, SysUser> commonPageBuilder = new CommonPageBuilder<>(UserQueryDTO.class);
        commonPageBuilder.appendEntity(queryParams.getEntity()).appendQuery(queryParams.getQuery()).appendPage(queryParams.getPage());
        //获取当前用户对应公司的用户
        //结果对象
        IPage<UserVO> pageList = new Page<>();
        IPage<SysUser> page = sysUserService.pageAll(commonPageBuilder.bulid());
        List<SysUser> Users = page.getRecords();
        pageList.setTotal(page.getTotal());
        pageList.setCurrent(page.getCurrent());
        pageList.setSize(page.getSize());
        //查询到结果 数据转换
        if (ObjectUtil.isNotNull(Users)) {
            pageList.setRecords(Users.stream().map(sysUser -> {
                UserVO userVO = new UserVO();
                BeanUtil.copyProperties(sysUser, userVO);
                return userVO;
            }).collect(Collectors.toList()));
        } else {
            pageList.setRecords(new ArrayList<>());
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, pageList);
    }

    /**
     * 查询用户列表信息--启用的用户
     *
     * @param queryParams
     * @return
     */
    public Result<List<UserVO>> queryUsers(UserQueryParams queryParams) {
        Assert.notNull(queryParams, SysMsgCodeConstant.Error.ERR10000001);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        UserQueryDTO queryDTO = new UserQueryDTO();
        BeanUtil.copyProperties(queryParams, queryDTO);
        queryDTO.setStatus(YesOrNoEnum.YES.getValue());
        List<SysUser> Users = sysUserService.list(queryDTO, loginUser);
        //查询对象
        List<UserVO> list = new ArrayList<>();
        if (ObjectUtil.isNotNull(Users)) {
            list = Users.stream().map(sysUser -> {
                UserVO UserVO = new UserVO();
                BeanUtil.copyProperties(sysUser, UserVO);
                return UserVO;
            }).collect(Collectors.toList());
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, list);
    }


    /**
     * 创建用户
     *
     * @param createParams 创建对象
     * @return Result
     */
    @Transactional
    public Result<String> createUser(UserCreateParams createParams) {
        ValidateUtil.validate(createParams);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //判断手机号码是否存在
        SysUser sysUser = sysUserService.queryUserByMobile(createParams.getMobile());
        String userCode;
        if (ObjectUtil.isNull(sysUser)) {
            UserBuilder userBuilder = new UserBuilder();
            userBuilder.append(createParams).appendStatus(YesOrNoEnum.YES.getValue()).appendCreate(loginUser);
            //保存用户信息
            if (!sysUserService.save(userBuilder.bulid())) {
                log.info("保存用户接口异常,参数:{}", JSON.toJSONString(userBuilder.bulid()));
                throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
            }
            //保存登录信息
            LoginBuilder loginBuilder = new LoginBuilder();
            loginBuilder.appendCode(userBuilder.getCode()).appendLoginName(createParams.getMobile()).appendCreate(loginUser);
            if (!sysLoginService.save(loginBuilder.bulid())) {
                log.info("保存登录信息接口异常,参数:{}", JSON.toJSONString(userBuilder.bulid()));
                throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
            }
            userCode = userBuilder.getCode();
        } else {
            //判断用户是否已经在公司下面
            userCode = sysUser.getUserCode();
        }
        SysUserCompany userCompany = sysUserCompanyService.queryLink(userCode, loginUser.getCompanyCode());
        if (ObjectUtil.isNull(userCompany)) {
            //创建用户与公司的关联--当前公司下面
            log.info("公司编码:{}", loginUser.getCompanyCode());
            UserCompanyBuilder userCompanyBuilder = new UserCompanyBuilder();
            userCompanyBuilder.appendCompanyCode(loginUser.getCompanyCode())
                    .appendDeptCode(createParams.getDeptCode())
                    .appendUserCode(userCode).appendCreate(loginUser);
            if (!sysUserCompanyService.save(userCompanyBuilder.bulid())) {
                log.info("保存登录信息接口异常,参数:{}", JSON.toJSONString(userCompanyBuilder.bulid()));
                throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
            }
        }
        //判断职位是否存在
        SysPosition sysPosition = sysPositionService.queryGPositionByPositionCode(createParams.getPositionCode());
        new PositionCheck(sysPosition).checkNull(SysMsgCodeConstant.Error.ERR10000002);
        //保存职位信息
        UserPositionBuilder userPositionBuilder = new UserPositionBuilder();
        userPositionBuilder.appendCode(userCode).appendCompanyCode(loginUser.getCompanyCode())
                .appendPositionCode(createParams.getPositionCode()).appendCreate(loginUser);
        if (!sysUserPositionService.save(userPositionBuilder.bulid())) {
            log.info("保存职位接口异常,参数:{}", JSON.toJSONString(userPositionBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        //保存扩展信息
        UserInfoDTO userInfoDTO = new UserInfoDTO();
        BeanUtil.copyProperties(createParams,userInfoDTO);
        //保存扩展信息
        List<TemplateRecord> templateRecords = new TemplateFactory<UserInfoDTO>().readTemplate(userInfoDTO);
        if (ObjectUtil.isNotEmpty(templateRecords)) {
            sysUserInfoService.saveBatch(templateRecords.stream().map(templateRecord -> {
                UserInfoBuilder UserInfoBuilder = new UserInfoBuilder();
                UserInfoBuilder.append(templateRecord).appendCode(userCode).appendCreate(loginUser).appendCompanyCode(loginUser.getCompanyCode());
                return UserInfoBuilder.bulid();
            }).collect(Collectors.toList()));
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, userCode);
    }

    /**
     * 编辑用户
     *
     * @param editParams 编辑对象
     * @return Result
     */
    @Transactional
    public Result<String> editUser(UserEditParams editParams) {
        ValidateUtil.validate(editParams);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        UserBuilder userBuilder = new UserBuilder();
        userBuilder.append(editParams).appendEdit(loginUser);
        //编辑用户信息
        if (!sysUserService.edit(userBuilder.bulid(), loginUser)) {
            log.info("编辑用户接口异常,参数:{}", JSON.toJSONString(userBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        //更新职位信息
        SysUserPosition sysPosition = sysUserPositionService.queryPositionByLogin(editParams.getUserCode(), loginUser.getCompanyCode());
        if (ObjectUtil.isNull(sysPosition)) {
            //保存职位信息
            UserPositionBuilder userPositionBuilder = new UserPositionBuilder();
            userPositionBuilder.appendCode(editParams.getUserCode()).appendCompanyCode(loginUser.getCompanyCode())
                    .appendPositionCode(editParams.getPositionCode()).appendCreate(loginUser);
            if (!sysUserPositionService.save(userPositionBuilder.bulid())) {
                log.info("保存职位接口异常,参数:{}", JSON.toJSONString(userPositionBuilder.bulid()));
                throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
            }
        } else {
            UserPositionBuilder userPositionBuilder = new UserPositionBuilder();
            userPositionBuilder.appendCode(editParams.getUserCode()).appendCompanyCode(loginUser.getCompanyCode())
                    .appendPositionCode(editParams.getPositionCode()).appendEdit(loginUser);
            if (!sysUserPositionService.changePosition(userPositionBuilder.bulid())) {
                log.info("更新职位接口异常,参数:{}", JSON.toJSONString(userPositionBuilder.bulid()));
                throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
            }
        }
        //删除信息
        sysUserInfoService.deleteUserInfo(editParams.getUserCode(), loginUser);
        //保存扩展信息
        UserInfoDTO userInfoDTO = new UserInfoDTO();
        BeanUtil.copyProperties(editParams,userInfoDTO);
        //保存扩展信息
        List<TemplateRecord> templateRecords = new TemplateFactory<UserInfoDTO>().readTemplate(userInfoDTO);
        if (ObjectUtil.isNotEmpty(templateRecords)) {
            sysUserInfoService.saveBatch(templateRecords.stream().map(templateRecord -> {
                UserInfoBuilder UserInfoBuilder = new UserInfoBuilder();
                UserInfoBuilder.append(templateRecord).appendCode(editParams.getUserCode()).appendEdit(loginUser).appendCompanyCode(loginUser.getCompanyCode());
                return UserInfoBuilder.bulid();
            }).collect(Collectors.toList()));
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, userBuilder.getCode());
    }

    /**
     * 编辑用户
     *
     * @param editParams 编辑对象
     * @return Result
     */
    @Transactional
    public Result<String> editMy(MyEditParams editParams) {
        ValidateUtil.validate(editParams);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        editParams.setUserCode(loginUser.getUserCode());
        UserBuilder userBuilder = new UserBuilder();
        userBuilder.append(editParams).appendEdit(loginUser);
        //编辑用户信息
        if (!sysUserService.edit(userBuilder.bulid(), loginUser)) {
            log.info("编辑用户接口异常,参数:{}", JSON.toJSONString(userBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, userBuilder.getCode());
    }


    /**
     * 开启用户--支队当前公司有效
     *
     * @param userOpenCloseParams 用户编码
     * @return Result
     */
    @Transactional
    public Result<String> openUser(UserOpenCloseParams userOpenCloseParams) {
        ValidateUtil.validate(userOpenCloseParams);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        if (!sysUserCompanyService.updateStatus(userOpenCloseParams.getUserCode(), userOpenCloseParams.getDeptCode(), YesOrNoEnum.YES, loginUser)) {
            log.info("编辑用户接口异常,参数:{}", JSON.toJSONString(userOpenCloseParams));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, userOpenCloseParams.getUserCode());
    }

    /**
     * 开启用户--支队当前公司有效
     *
     * @param userOpenCloseParams 用户编码
     * @return Result
     */
    @Transactional
    public Result<String> closeUser(UserOpenCloseParams userOpenCloseParams) {
        ValidateUtil.validate(userOpenCloseParams);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        if (!sysUserCompanyService.updateStatus(userOpenCloseParams.getUserCode(), userOpenCloseParams.getDeptCode(), YesOrNoEnum.NO, loginUser)) {
            log.info("编辑用户接口异常,参数:{}", JSON.toJSONString(userOpenCloseParams));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, userOpenCloseParams.getUserCode());
    }

    /**
     * 用户详情
     *
     * @param userCode 用户编码
     * @return Result
     */
    public Result<UserVO> viewUser(String userCode,String companyCode) {
        ValidateUtil.hasLength(userCode, "参数[userCode]不能为空");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        if(StrUtil.isBlank(companyCode)){
            companyCode = loginUser.getCompanyCode();
        }
        //获取权限信息
        SysUser sysUser = sysUserService.queryUserByUserCode(userCode, loginUser);
        new UserCheck(sysUser).checkNull(SysMsgCodeConstant.Error.ERR10000002);
        UserVO userVO = new UserVO();
        BeanUtil.copyProperties(sysUser, userVO);
        //设置附加信息
        List<TemplateRecord> templateRecords = sysUserInfoService.queryUserInfoByUserCode(userCode, loginUser);
        UserInfoDTO userInfoDTO = new TemplateFactory<UserInfoDTO>().readObject(templateRecords, UserInfoDTO.class);
        if (ObjectUtil.isNotNull(userInfoDTO)) {
            BeanUtil.copyProperties(userInfoDTO, userVO);
        }
        //获取职位信息
       SysPosition userPosition = userService.queryPositionByLogin(userCode,companyCode);
        if(ObjectUtil.isNotNull(userPosition)){
            userVO.setPositionCode(userPosition.getPositionCode());
            userVO.setPositionName(userPosition.getPositionName());
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, userVO);
    }


    /**
     * 用户授权
     *
     * @param authParams 用户授权
     * @return Result
     */
    @Transactional
    public Result<String> addAuth(UserAuthParams authParams) {
        ValidateUtil.validate(authParams);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //查询用户是否拥有该角色
        //是否拥有全部数据权限
        if (!loginUser.isAllData()) {
            //判断角色是否存在
            SysRole sysRole = sysRoleService.queryRoleByRoleCode(authParams.getRoleCode(), loginUser);
            new RoleCheck(sysRole).checkNull(SysMsgCodeConstant.Error.ERR10000002);
            //判断用户是否存在
            SysUser sysUser = sysUserService.queryUserByUserCode(authParams.getUserCode(), loginUser);
            new UserCheck(sysUser).checkNull(SysMsgCodeConstant.Error.ERR10000002);
            //判断是否有角色权限
            if (!sysUserRoleService.queryUserHasRole(loginUser.getUserCode(), authParams.getRoleCode())
                    && ObjectUtil.isNull(sysRoleService.queryRoleByRoleCode(authParams.getRoleCode(),loginUser))) {
                log.info("查询角色权限异常,参数:{}", authParams.getRoleCode());
                throw BusinessExceptionFactory.newException(SysMsgCodeConstant.Error.ERR10000010);
            }
        }
        UserRoleBuilder userRoleBuilder = new UserRoleBuilder();
        userRoleBuilder.append(authParams).appendCreate(loginUser);
        //角色菜单关联
        if (!sysUserRoleService.save(userRoleBuilder.bulid())) {
            log.info("角色角色关联接口异常,参数:{}", JSON.toJSONString(userRoleBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, "true");
    }

    /**
     * 删除角色授权
     *
     * @param authParams 授权对象
     * @return Result
     */
    @Transactional
    public Result<String> removeAuth(UserAuthParams authParams) {
        ValidateUtil.validate(authParams);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //是否拥有全部数据权限
        if (!loginUser.isAllData()) {
            //判断用户是否存在
            SysUser sysUser = sysUserService.queryUserByUserCode(authParams.getUserCode(), loginUser);
            new UserCheck(sysUser).checkNull(SysMsgCodeConstant.Error.ERR10000002);
        }
        UserRoleBuilder userRoleBuilder = new UserRoleBuilder();
        userRoleBuilder.append(authParams).appendEdit(loginUser).delete();
        //删除角色菜单关联
        if (!sysUserRoleService.delete(userRoleBuilder.bulid(), loginUser)) {
            log.info("删除角色用户关联接口异常,参数:{}", JSON.toJSONString(userRoleBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, "true");
    }


    /**
     * 重置密码
     *
     * @param userCode 用户编码
     * @return Result
     */
    @Transactional
    public Result<String> resetPassword(String userCode) {
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //判断用户是否存在
        SysUser sysUser = sysUserService.queryUserByUserCode(userCode, loginUser);
        new UserCheck(sysUser).checkNull(SysMsgCodeConstant.Error.ERR10000002);
        LoginBuilder loginBuilder = new LoginBuilder();
        loginBuilder.appendCode(userCode).reset(sysUser.getMobile()).appendEdit(loginUser);
        //重置密码
        if (!sysLoginService.edit(loginBuilder.bulid(), loginUser)) {
            log.info("重置密码异常,参数:{}", JSON.toJSONString(loginBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, userCode);
    }

    /**
     * 修改密码
     *
     * @param updatePasswordParams
     * @return
     */
    public Result<String> updatePassword(@Valid UpdatePasswordParams updatePasswordParams) {
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //判断用户是否存在
        SysUser sysUser = sysUserService.queryUserByUserCode(loginUser.getUserCode(), loginUser);
        new UserCheck(sysUser).checkNull(SysMsgCodeConstant.Error.ERR10000002);
        //核对密码
        SysLogin sysLogin = sysLoginService.queryByLogin(sysUser.getMobile(), updatePasswordParams.getOldPassword());
        new AbstractCheck<>(sysLogin).checkNull("原始密码不正确");
        LoginBuilder loginBuilder = new LoginBuilder();
        loginBuilder.append(updatePasswordParams).appendCode(loginUser.getUserCode()).appendEdit(loginUser);
        //重置密码
        if (!sysLoginService.edit(loginBuilder.bulid(), loginUser)) {
            log.info("修改密码异常,参数:{}", JSON.toJSONString(loginBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, loginUser.getUserCode());
    }
}
